package com.lzx.iteam;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.AtDateBean;
import com.lzx.iteam.bean.DateBean;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetApprovalCalendarMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.widget.CustomGridView;
import com.lzx.iteam.widget.schedulecalendar.SelectCalendarAdapter;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 12月 10日
 * Time: 下午2:50
 *
 * @QQ : 1234567890
 * **********************************
 */
public class SelectDateActivity extends MyBaseActivity implements View.OnClickListener,GestureDetector.OnGestureListener{

    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;

    @FindViewById(id = R.id.calendar_tv_year)
    private TextView mTvYear;
    @FindViewById(id = R.id.calendar_tv_month1)
    private TextView mTvMonth1;
    @FindViewById(id = R.id.calendar_tv_month2)
    private TextView mTvMonth2;
    @FindViewById(id = R.id.calendar_iv_previous)
    private ImageView mIvPrevious;
    @FindViewById(id = R.id.calendar_iv_next)
    private ImageView mIvNext;
    @FindViewById(id = R.id.calentar_gridview)
    private CustomGridView mGridView;

    private SelectCalendarAdapter calV = null;  // 日历adapter
    private GestureDetector gestureDetector = null;
    private PopupWindow mSelectPopupWindow;
    private HashMap<String,Object> mDatas;
    private HashMap<Long,DateBean> mSelectDates = new HashMap<>();

    private String mGroupId;
    private String currentDate = "";
    private String scheduleYear;    // 选择的年份
    private String scheduleMonth;   // 选择的月份
    private String scheduleDay;     // 选择的日子
    private Calendar c;
    private int jumpMonth = 0;      //每次滑动，增加或减去一个月,默认为0（即显示当前月）
    private int jumpYear = 0;       //滑动跨越一年，则增加或者减去一年,默认为0(即当前年)
    private int mYear;  // 跳转的年份
    private int mMonth; // 跳转的月份
    private int mDay;   // 跳转的日子
    private int year_c = 0;  // 当前的年份
    private int month_c = 0; // 当前的月份
    private int day_c = 0;   // 当前的日子
    private int mFormType;  //  考勤表类型,1.排班,0.固定
    private int mApprovalType = -1;  // 审批类型  1.出差，2.请假，3.外出，4.签到
    private int[] mIds = {R.id.iv_1,R.id.iv_2,R.id.iv_3,R.id.iv_4,R.id.iv_5,R.id.iv_6,R.id.iv_7};

    private final int GET_CALENDAR_LIST = 30000;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_CALENDAR_LIST:
                    if (msg.arg1 == 0){
                        mDatas = (HashMap<String, Object>) msg.obj;
                        mFormType = (int) mDatas.get("form_type");
                        calV.bindData(mDatas);
                        calV.bindSelectData(mSelectDates);
                    }else{
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState,R.layout.select_date_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mIvPrevious.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        mTvRight.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mTvTitle.setText("日期选择");
        mTvRight.setText("确定");
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mSelectDates = (HashMap<Long, DateBean>) intent.getSerializableExtra("select_date");
        mApprovalType = intent.getIntExtra("approval_type",-1);
        c = Calendar.getInstance();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        currentDate = sdf.format(date);  //当期日期
        year_c = Integer.parseInt(currentDate.split("-")[0]);
        month_c = Integer.parseInt(currentDate.split("-")[1]);
        day_c = Integer.parseInt(currentDate.split("-")[2]);

        mYear = year_c;
        mMonth = month_c;
        mDay = day_c;

        gestureDetector = new GestureDetector(this);
        calV = new SelectCalendarAdapter(this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c, mGroupId);
        if (mSelectDates != null){
            calV.bindSelectData(mSelectDates);
        }
        mGridView.setAdapter(calV);
        addTextToTopTextView();
        addGridView();
        getCalendarList();
    }

    private void getCalendarList(){
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_MONTH, mYear + "_" + mMonth));
        GetApprovalCalendarMsg msg = new GetApprovalCalendarMsg(mHandler.obtainMessage(GET_CALENDAR_LIST));
        msg.mApi = AsynHttpClient.API_EVENT_APPROVAL_CALENDAR;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_ll_back:
                finish();
                break;
            case R.id.calendar_iv_previous:
                changeView(false);
                break;
            case R.id.calendar_iv_next:
                changeView(true);
                break;
            case R.id.title_tv_right:
                savaSelectDate();
                break;
            case R.id.tv_date_all:
                setSelectDate(0);
                break;
            case R.id.tv_date_AM:
                setSelectDate(1);
                break;
            case R.id.tv_date_PM:
                setSelectDate(2);
                break;
            case R.id.tv_date_cancel:
                setSelectDate(-1);
                break;


        }
    }

    /**
     * 设置选中日期数据
     * @param type
     */
    private void setSelectDate(int type){
        long time = DateUtil.getOneDayBegin(mYear,mMonth,mDay);
        if (type == -1){
            mSelectDates.remove(time);
        }else{
            DateBean bean = new DateBean(time,type);
            mSelectDates.put(time,bean);
        }
        mSelectPopupWindow.dismiss();
        calV.bindSelectData(mSelectDates);
    }

    /**
     * 保存返回数据
     */
    private void savaSelectDate(){
        Intent intent = new Intent();
        intent.putExtra("select_date",mSelectDates);
        setResult(RESULT_OK,intent);
        finish();
    }


    /**
     *
     * @param flag  true: 下一个月  false: 上一个月
     */
    private void changeView(boolean flag) {
        if (flag) {
            //下一个月
            if (jumpMonth == 1){
                return;
            }
            jumpMonth++;
            mMonth++;
            if (mMonth > 12) {
                mMonth = 1;
                mYear++;
            }
        } else {
            //上一个月
            if (jumpMonth == -1){
                return;
            }
            jumpMonth--;
            mMonth--;
            if (mMonth < 1) {
                mMonth = 12;
                mYear--;
            }
        }
        updateView();
    }

    /**
     * 切换月份
     */
    private void addGridView() {

        mGridView.setOnTouchListener(new View.OnTouchListener() {
            //将gridview中的触摸事件回传给gestureDetector
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                return gestureDetector.onTouchEvent(event);
            }
        });

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //gridView中的每一个item的点击事件
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                //点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
                int startPosition = calV.getStartPositon();
                int endPosition = calV.getEndPosition();
                if (startPosition <= position + 7 && position <= endPosition - 7) {
                    scheduleDay = calV.getDateByClickItem(position).split("\\.")[0];  //这一天的阳历
//                    String scheduleLunarDay = calV.getDateByClickItem(position).split("\\.")[1];  //这一天的阴历
                    scheduleYear = calV.getShowYear();
                    scheduleMonth = calV.getShowMonth();
                    int year = Integer.parseInt(scheduleYear);
                    int month = Integer.parseInt(scheduleMonth);
                    mDay = Integer.parseInt(scheduleDay);

                    // TODO 外出只能选择一天
                    long time = DateUtil.getOneDayBegin(year,month,mDay);
                    if (mApprovalType == 3 && mSelectDates.size() > 0 && mSelectDates.get(time) == null){
                        showShortToast("外出日期仅限制在一天内");
                        return;
                    }

                    // TODO 固定排班的 非工作日不可选择
                    int weekDay = position % 7;
                    if (weekDay == 0){
                        weekDay = 7;
                    }
                    String workDay = (String) mDatas.get("date");

                    if (mFormType == 0 && !workDay.contains(weekDay + "") && !(weekDay == 6 && workSaturday(scheduleMonth + mDay))){
                        showShortToast("非工作日不可选择");
                        return;
                    }

                    // TODO 出差、请假、外出、加班 不可以选择
                    AtDateBean bean = (AtDateBean) mDatas.get(mDay + "");
                    if (bean != null) {
                        int status = bean.getStatus();
                        if (status == 3 || status == 4 || status == 5 || status == 7){
                            showShortToast("出差、请假、外出、加班 不可以选择");
                            return;
                        }
                        showPopupwindow(arg1,position % 7);
                    }else{
                        showPopupwindow(arg1,position % 7);
                    }

                }
            }

        });
    }

    /**
     * 2017 年
     * (2,4), (4,1) ,(5.27), (9,30) 这四个周六上班
     * @param selectDay
     * @return
     */
    private boolean workSaturday(String selectDay){
        if (selectDay.equals("24") || selectDay.equals("41") || selectDay.equals("527") || selectDay.equals("930")){
            return true;
        }else{
            return false;
        }

    }
    /**
     * 月份切换，刷新日历表
     */
    private void updateView() {
        addGridView();   //添加一个gridView
        calV = new SelectCalendarAdapter(this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c);
        mGridView.setAdapter(calV);
        addTextToTopTextView();
        Log.d("Year and Month", "changeView  Month == " + mMonth + "   Year  == " + mYear);
        getCalendarList();
    }

    /**
     * 更新年月
     *
     * @param
     */
    public void addTextToTopTextView() {
        mTvYear.setText(calV.getShowYear() + "年");
        int month = Integer.parseInt(calV.getShowMonth());
        int month1 = month / 10;
        int month2 = month % 10;
        mTvMonth1.setText(month1 + "");
        mTvMonth2.setText(month2 + "");

    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() - e2.getX() > 120) {
            //下一个月
            if (jumpMonth == 1){
                return true;
            }
            jumpMonth++;
            mMonth++;
            if (mMonth > 12) {
                mMonth = 1;
                mYear++;
            }
            updateView();
            return true;
        } else if (e1.getX() - e2.getX() < -120) {
            //上一个月
            if (jumpMonth == -1){
                return true;
            }
            jumpMonth--;
            mMonth--;
            if (mMonth < 1) {
                mMonth = 12;
                mYear--;
            }
            updateView();
            return true;
        }
        return false;
    }


    /**
     * 弹出操作框
     * @param view
     * @param position
     */
    private void showPopupwindow(View view,int position){

        final View mainView = LayoutInflater.from(this).inflate(R.layout.pop_select_date_layout, null);
        ImageView image = (ImageView) mainView.findViewById(mIds[position]);
        image.setVisibility(View.VISIBLE);

        TextView tvAll = (TextView) mainView.findViewById(R.id.tv_date_all);
        TextView tvAM = (TextView) mainView.findViewById(R.id.tv_date_AM);
        TextView tvPM = (TextView) mainView.findViewById(R.id.tv_date_PM);
        TextView tvCancel = (TextView) mainView.findViewById(R.id.tv_date_cancel);

        tvAll.setOnClickListener(this);
        tvAM.setOnClickListener(this);
        tvPM.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

        mSelectPopupWindow = new PopupWindow(mainView,
              WindowManager.LayoutParams.MATCH_PARENT,
              WindowManager.LayoutParams.WRAP_CONTENT);
        mSelectPopupWindow.setFocusable(true);
        mSelectPopupWindow.setOutsideTouchable(true);
        mSelectPopupWindow.setBackgroundDrawable(new ColorDrawable(
              Color.TRANSPARENT));
        mSelectPopupWindow.showAsDropDown(view, 0, -24);

    }
}
